//
//  Music_list_vc.m
//  ainkjj
//
//  Created by MAX on 2020/5/12.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Music_list_vc.h"
#import "Music_list_tv_cell.h"


#import "GetMusic.h"
#import "GetMusic_tv_cell.h"
#import "GetMusic_category_list.h"
typedef void(^MusicListSelectedRow)(App_getMusicListMusic_list *currentSong);

@interface Music_list_vc ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIButton *btnCancel;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, assign)NSUInteger currentIndex;
@property (nonatomic, copy) MusicListSelectedRow selectedRowBlk;
@property (nonatomic, copy) NSString *audio_execute_status;
@property (nonatomic, assign)int refreshIndex;
@property (nonatomic, assign)NSInteger totalPage;
@end

@implementation Music_list_vc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArr = NSMutableArray.new;
    
    self.tableView = [UITableView new];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"GetMusic_tv_cell" bundle:nil] forCellReuseIdentifier:@"GetMusic_tv_cell"];
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
    
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    
    // tableView.separatorColor = UIColor.redColor;
    
    //[tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    //    self.tableView.mj_header=[MJRefreshNormalHeader  headerWithRefreshingTarget:self refreshingAction:@selector(req)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//    [self req];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(current_song_change:) name:@"current_song_change_to_list_vc" object:nil];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"current_song_change_to_list_vc" object:nil];
}
- (void)current_song_change:(NSNotification *)noti{
    NSDictionary *userInfo = noti.userInfo;
    GetMusicList *model = [userInfo objectForKey:@"current_song_change_to_list_vc"];
    DLog(@"%@", model.title);

    for (GetMusicList *song in self.dataArr) {
        //        song.isSelected =
        if (model.ID == song.ID && [model.title isEqualToString:song.title]) {
            song.isSelected = YES;
            
        }else{
            song.isSelected = NO;
        }
    }
    
    [self.tableView reloadData];

}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.tableView.frame = self.view.bounds;
}

- (void)req{
    
    //  请求服务器，获取列表，刷新tv
    self.refreshIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:@"100" forKey:@"page_size"];
    [dict setObject:@"1" forKey:@"category_id"];
    
    [PPHTTPRequest req:@"api/app/getMusic" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            GetMusic *model = [GetMusic mj_objectWithKeyValues:response];
            
            if (!model.data.list || model.data.list.count == 0) {
                [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
            }else{
                [self hideEmptyView];
                self.totalPage = model.data.page_info.page_total;
                self.dataArr = model.data.list.mutableCopy;

                for (NSInteger i = 0; i < self.dataArr.count; i++) {
                    GetMusicList *m = self.dataArr[i];
                    m.index = i;
                }
            }
            
        }else{
            
            [QMUITips showError:response[@"error_msg"] ];
        }
        
        [self endMjRefresh];
        
    } failure:^(NSError *error) {
        [self endMjRefresh];
        
        [QMUITips showError:[error localizedDescription] ];
        
    }];
    
    
   
    
}
- (void)setCategory_id:(NSString *)category_id{
    _category_id = category_id;
    GetMusic_category_list *req = [[GetMusic_category_list alloc] init_page:@"1" page_size:@"100" category_id:category_id];
    [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *response = request.responseJSONObject;
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            GetMusic *model = [GetMusic mj_objectWithKeyValues:response];
            
            if (!model.data.list || model.data.list.count == 0) {
                [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
            }else{
                [self hideEmptyView];
                self.totalPage = model.data.page_info.page_total;
                self.dataArr = model.data.list.mutableCopy;
                
                for (NSInteger i = 0; i < self.dataArr.count; i++) {
                    GetMusicList *m = self.dataArr[i];
                    m.index = i;
                }
            }
            
        }else{
            
            [QMUITips showError:response[@"error_msg"] ];
        }
        
        [self endMjRefresh];
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}
- (BOOL)allowsDragToDismiss {
    return NO;
}
- (void)loadMoreData{
    self.refreshIndex++;
    
    if (self.refreshIndex > self.totalPage) {
        // 拿到当前的上拉刷新控件，变为没有更多数据的状态
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }else{
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        [dict setObject:@(self.refreshIndex).stringValue forKey:@"page"];
        [dict setObject:@"100" forKey:@"page_size"];
        [dict setObject:@"1" forKey:@"category_id"];
        
        
        [PPHTTPRequest req:@"api/app/getMusic" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                GetMusic *model = [GetMusic mj_objectWithKeyValues:response];

                if (!model.data) {
                    [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
                }else{
                    [self hideEmptyView];
                    [self.dataArr addObjectsFromArray:model.data.list];
                    for (NSInteger i = 0; i < self.dataArr.count; i++) {
                        GetMusicList *m = self.dataArr[i];
                        m.index = i;
                    }
                }
                
                
                
                
            }
            else{
                
                
                [QMUITips showError:response[@"error_msg"] ];
                
            }
            [self endMjRefresh];
            
        } failure:^(NSError *error) {
            [self endMjRefresh];
            
            [QMUITips showError:[error localizedDescription] ];
            
        }];
        
    }
    
}

- (void)endMjRefresh{
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [self.tableView reloadData];
    });
    
    if (self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
    
    
    if (self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    
}
#pragma mark - ================== table view data source delegate ==================
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GetMusic_tv_cell *cell = [tableView dequeueReusableCellWithIdentifier:@"GetMusic_tv_cell"];
    if (!cell) {
        cell = [[GetMusic_tv_cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GetMusic_tv_cell"];
    }
    GetMusicList *list = self.dataArr[indexPath.row];
    cell.model = list;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _currentIndex = indexPath.row;

    GetMusicList *list = self.dataArr[indexPath.row];

    // 样式
    for (GetMusicList *song in self.dataArr) {
        if ([list isEqual:song]) {
            song.isSelected = YES;
        }else{
            song.isSelected = NO;
        }
    }
    [tableView reloadData];
    //
    [[NSNotificationCenter defaultCenter] postNotificationName:@"current_song_change_to_Device_vc" object:nil userInfo:@{@"current_song_change_to_Device_vc" : list}];


}
@end
